package com.ming.shiro;

import com.ming.redsi.RedisUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;

/**
 * 重写 shiro 缓存 一些增删改查
 * 与 ShiroCaheManager 一起使用
 * @author MING
 * @date 2018/9/12 15:41
 */
@Component
public class ShiroCache<K, V> implements Cache<K, V> {
    @Resource
    private RedisUtil redisUtil;

    private final String CACHE_PREFIX = "shiro-cache:";

    private String getKey(K k) {
        return CACHE_PREFIX + k;
    }

    //    TODO
//    设置二级缓存，不要每次都从redis中去读取
    @Override
    public V get(K k) throws CacheException {
        System.out.println("从redis获取数据" + "========");
        byte[] value = redisUtil.getByte(getKey(k).getBytes());
        if (value != null) {
            return (V) SerializationUtils.deserialize(value);
        }
        return null;
    }

    @Override
    public V put(K k, V v) throws CacheException {
        byte[] key = getKey(k).getBytes();
        byte[] value = SerializationUtils.serialize(v);
        redisUtil.setByte(key, value);
        return v;
    }

    @Override
    public V remove(K k) throws CacheException {
        byte[] key = getKey(k).getBytes();
        V value = get(k);
        redisUtil.delByte(key);
        if (value != null) {
            return value;
        }
        return null;
    }

    @Override
    public void clear() throws CacheException {
        //不要重写此方法，除非redis中存储的是shiro的角色权限数据，要会被清空
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<K> keys() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }
}
